<?php
namespace app\index\controller;

use think\Controller;
use think\Cache;
use think\Request;
use think\Config;
use think\Session;
use think\Log;
use qy_weixin\WXBizMsgCrypt;


class Qyweixin extends Controller
{

    function __construct() {
        parent::__construct();
        $this->Token = 'FyaJQks6lAQfcwSrhob9xdUj1u';
        $this->EncodingAESKey = 'p7fQrKEqWrrSli8Iy4XEPlFhUsM6VT7DEizHHz3uM42';
    }

    //获取企业应用号的access_token
    //空为获取应用号的access_token；1为获取通讯录的access_token
    function access_token($type=''){
        if($type==1){
            $access_token = Cache::get('qy_txl_access_token');
        }else{
            $access_token = Cache::get('qy_access_token');
        }
        if(empty($access_token)){
            $dao = new \app\model\Qyweixin();
            $access_token = $dao->access_token($type);//获取网页授权access_token
            if($access_token){
                if($type==1){
                    Cache::set('qy_txl_access_token', $access_token, 6000);
                }else{
                    Cache::set('qy_access_token', $access_token, 6000);
                }

            }
        }
        return $access_token;
    }

    //创建成员
    public function add_user(){
        $dao = new \app\model\Qyweixin();
        $data['userid']='huangxiusheng';//成员UserID。对应管理端的帐号，企业内必须唯一。不区分大小写，长度为1~64个字节
        $data['name']='黄修省';//成员名称。长度为1~64个字节
        $data['mobile']='13262828732';//手机号码。企业内必须唯一，mobile/email二者不能同时为空
        $data['department']=1;//成员所属部门id列表,不超过20个
        $result_status = $dao->add_user($this->access_token('1'),$data);
        return json($result_status);
    }

    //删除成员
    public function del_user(){
        $dao = new \app\model\Qyweixin();
        $userid = 'huangxiusheng';
        $result_status = $dao->del_user($this->access_token('1'),$userid);
        return json($result_status);
    }

    //创建部门
    public function add_department(){
        $dao = new \app\model\Qyweixin();
        $data['name']='部门api2';//	部门名称。长度限制为1~64个字节，字符不能包括\:?”<>｜
        $data['parentid']=1;//父部门id
//下面内容如果为空，请不要传值，传空值微信会返回错误码-60009  data:20170906
//        $data['order']='';//在父部门中的次序值。order值大的排序靠前。有效的值范围是[0, 2^32)
//        $data['id']='';//部门id，整型。指定时必须大于1，否则自动生成
        $result_lists = $dao->add_department($this->access_token(1),$data);
        return json($result_lists);
    }

    //获取部门列表
    public function get_department_lists(){
        $dao = new \app\model\Qyweixin();
        $result_lists = $dao->get_department_lists($this->access_token(1));
        return json($result_lists);
    }

    //删除部门（只能单个删除）
    public function del_department(){
        $dao = new \app\model\Qyweixin();
        $departmentid = '2';
        $department_ststus = $dao->del_department($this->access_token('1'),$departmentid);
        return json($department_ststus);
    }

    //添加标签
    public function add_tags(){
        $dao = new \app\model\Qyweixin();
        $data['tagname']='标签api3';//标签名称
//下面内容如果为空，请不要传值，传空值微信会把你传的tagname再次转义(亲测，包括上面那个应该属于bug，估计微信会很快修复吧)  data:20170906
//        $data['tagid']='';//标签id，非负整型，指定此参数时新增的标签会生成对应的标签id，不指定时则以目前最大的id自增。
        $result_lists = $dao->add_tags($this->access_token(),$data);
        return json($result_lists);
    }

    //获取标签列表
    public function get_tags_lists(){
        $dao = new \app\model\Qyweixin();
        $tags_lists = $dao->get_tags_lists($this->access_token());
        return json($tags_lists);
    }

    //删除标签（只能单个删除）
    public function del_tag(){
        $dao = new \app\model\Qyweixin();
        $tagid = '4';
        $tags_ststus = $dao->del_tag($this->access_token(),$tagid);
        return json($tags_ststus);
    }

    //消息接口定义
    public function news_define(){
        Config::load(APP_PATH.'other.php');
        $config = Config::get('qyweixin');//获取企业微信配置
        $dao = new \app\model\Qyweixin();
        $data['totag']=1;
        $data['msgtype']='text';
        $data['agentid']=$config['AgentId'];
        $content = '你的快递已到，请携带工卡前往邮件中心领取。\n出发前可查看<a href=\"http:\//work.weixin.qq.com\">邮件中心视频实况</a>，聪明避开排队。';
        $data['text']['content']=urlencode($content);
        $json_data = urldecode(json_encode($data));
        $result_lists = $dao->news_define($this->access_token(),$json_data);
        return json($result_lists);
    }

    //微信企业号接收消息
    public function get_qyweixin_news(){
        Config::load(APP_PATH.'other.php');
        $config = Config::get('qyweixin');//获取企业微信配置

        $sVerifyEchoStr = $this->request->get("echostr");
        $sVerifyMsgSig = $this->request->get("msg_signature");
        $sVerifyTimeStamp = $this->request->get("timestamp");
        $sVerifyNonce = $this->request->get("nonce");
        $sEchoStr = '';

        //调用微信下载的那个类包
        $wxcpt = new \qy_weixin\WXBizMsgCrypt($this->Token, $this->EncodingAESKey, $config['corpid']);
        $errCode1 = $wxcpt->WXBizMsgCrypt($this->Token, $this->EncodingAESKey, $config['corpid']);

        if(!empty($echostr)){//验证url有效性
            $errCode = $wxcpt->VerifyURL($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $sVerifyEchoStr, $sEchoStr);
            if ($errCode == 0) {
                echo $sEchoStr;exit;
            } else {
                print("ERR: " . $errCode . "\n\n");exit;
            }
        }
        $sReqMsgSig = $this->request->get("msg_signature");
        $sReqTimeStamp = $this->request->get("timestamp");
        $sReqNonce = $this->request->get("nonce");
        // post请求的密文数据
        $sReqData = file_get_contents("php://input"); //接收post数据

        $sMsg = "";  // 解析之后的明文
        $errCode = $wxcpt->DecryptMsg($sReqMsgSig, $sReqTimeStamp, $sReqNonce, $sReqData, $sMsg);
        if ($errCode == 0) {
            // 解密成功，sMsg即为xml格式的明文
            $sMsg=html_entity_decode($sMsg);
            $xml = new \DOMDocument();
            $xml->loadXML($sMsg);

            $tousername = $xml->getElementsByTagName('ToUserName')->item(0)->nodeValue;//微信corpid
            $msgtype = $xml->getElementsByTagName('MsgType')->item(0)->nodeValue;//消息类型
            $createtime = $xml->getElementsByTagName('CreateTime')->item(0)->nodeValue;//发送时间
            $msgid = $xml->getElementsByTagName('MsgId')->item(0)->nodeValue;//消息id
            $agentid = $xml->getElementsByTagName('AgentID')->item(0)->nodeValue;//企业微信应用AgentId
            $fromusername = $xml->getElementsByTagName('FromUserName')->item(0)->nodeValue;//发送人的userid
            if($msgtype=='text'){
                $content = $xml->getElementsByTagName('Content')->item(0)->nodeValue;//内容
                $reply_info['content'] = $content;
            }

            $reply_info['tousername'] = $tousername;
            $reply_info['msgtype'] = $msgtype;
            $reply_info['createtime'] = $createtime;
            $reply_info['msgid'] = $msgid;
            $reply_info['agentid'] = $agentid;
            $reply_info['fromusername'] = $fromusername;
            $reply_info['sVerifyTimeStamp'] = $sVerifyTimeStamp;
            $reply_info['sReqNonce'] = $sReqNonce;

            $this->qyweixin_reply_news($reply_info);
        } else {
            print("ERR: " . $errCode . "\n\n");
        }
    }
    //消息回复
    function qyweixin_reply_news($reply_info){
        Config::load(APP_PATH.'other.php');
        $config = Config::get('qyweixin');//获取企业微信配置
        //调用微信下载的那个类包
        $wxcpt = new \qy_weixin\WXBizMsgCrypt($this->Token, $this->EncodingAESKey, $config['corpid']);
        $errCode1 = $wxcpt->WXBizMsgCrypt($this->Token, $this->EncodingAESKey, $config['corpid']);
        if($reply_info['msgtype']=='text'){
            $content = '你发送内容是:'.$reply_info['content'];
        }elseif($reply_info['msgtype']=='image'){
            $content = '你发的是图片！';
        }elseif($reply_info['msgtype']=='voice'){
            $content = '你发的是语音！';
        }elseif($reply_info['msgtype']=='video'){
            $content = '你发的是视频！';
        }elseif($reply_info['msgtype']=='news'){
            $content = '这是一个比较高大上的图文消息！';
        }else{
            $content = '暂时不能识别你发的内容！';
        }
        $sRespData =
            "<xml>
                <ToUserName><![CDATA[".$reply_info['fromusername']."]]></ToUserName>
                <FromUserName><![CDATA[".$reply_info['tousername']."]]></FromUserName>
                <CreateTime>".$reply_info['createtime']."</CreateTime>
                <MsgType><![CDATA[text]]></MsgType>
                <Content><![CDATA[".$content."]]></Content>
                <MsgId><![CDATA[".$reply_info['msgid']."]]></MsgId>
                <AgentID><![CDATA[".$reply_info['agentid']."]]></AgentID>
            </xml>";

        $sEncryptMsg = ""; //xml格式的密文
        $errCode = $wxcpt->EncryptMsg($sRespData, $reply_info['sVerifyTimeStamp'], $reply_info['sReqNonce'], $sEncryptMsg);
        if ($errCode == 0) {
            $result = $sEncryptMsg;
            echo $result;exit;

            // TODO:
            // 加密成功，企业需要将加密之后的sEncryptMsg返回
            // HttpUtils.SetResponce($sEncryptMsg);  //回复加密之后的密文
        } else {
            print("ERR: " . $errCode . "\n\n");
            // exit(-1);
        }
    }
}


